const db = require('../config/db')
const productModel = '../schema/product'
const orderModel = '../schema/orderlist'
const commonUserModel = '../schema/common_user'
const addressModel = '../schema/address'
const Mall = db.MallSequelize   //引入数据库
const product = Mall.import(productModel)  //实例化product
const orderlist = Mall.import(orderModel)  //实例化order
const common_user = Mall.import(commonUserModel)
const address = Mall.import(addressModel)
common_user.hasMany(orderlist)
orderlist.belongsTo(common_user)
product.hasOne(orderlist)
orderlist.belongsTo(product)
address.hasOne(orderlist)
orderlist.belongsTo(address)
// 获取全部订单
const getOrders = async () => {
  const result = await orderlist.findAll(
    {
      include: [product, common_user, address],
      order: [['created_at', 'desc']]
    }
  )
  return result
}
// 获取全部订单
const getAllOrder = async (query) => {
  let page = Number(query.page)
  let limit = Number(query.limit)
  const result = await orderlist.findAndCountAll(
    {
      include: [product, common_user],
      offset: parseInt(page*10)*parseInt(limit/10),
      limit: limit
    }
  )
  return result
}
// 根据订单id获取订单
const getOrderById = async (id) => {
  const result = await orderlist.findAll(
    {
      include: [product, common_user, address],
      where: {
        order_id: id
      }
    }
  )
  return result
}
// 创建订单
const addOrder = async (data) => {
  await orderlist.create({
    order_id: data.order_id,
    common_user_id: data.common_user_id,
    product_id: data.product_id,
    status: data.status,
    pay_type: data.pay_type,
    send_type: data.send_type,
    total: data.total,
    count: data.count,
    order_id: data.order_id,
    address_id: data.address_id
  })
  return true
}
// 修改订单状态
const updateOrderStatus = async (id, data) => {
  await orderlist.update(
    {
      status: data.status
    },
    {
      where: {
        order_id: id
      }
    }
  )
  return true
}
// 根据搜索关键字获取用户
const getOrderByKeyWords = async (keywords) => {
  if(keywords.order_id) {
    const result = await orderlist.findAll(
      { 
        where: {
          order_id: Number(keywords.order_id)
        } 
      },
    )
    return result
  }
}
module.exports = {
  getOrders,
  getAllOrder,
  getOrderById,
  addOrder,
  updateOrderStatus,
  getOrderByKeyWords
}